﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    camera(nullptr)
{
    ui->setupUi(this);

    //init cam combobox
    ui->comboBox_cam->addItem(QString::fromLocal8Bit("选择摄像头"));
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    foreach (const QCameraInfo &cameraInfo, cameras) {
        ui->comboBox_cam->addItem(cameraInfo.description());
        qDebug()<<"Camera add. "<<cameraInfo.description() + cameraInfo.deviceName();
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_preview_toggled(bool checked)
{
    qDebug()<<__FUNCTION__<<" checked:"<<checked;
    camview* pp = camview::GetInstance(this);
    if(checked)
    {
        pp->show();
    }
    else
    {
        pp->hide();
    }
}

void MainWindow::on_comboBox_cam_currentIndexChanged(int index)
{
    qDebug()<<__FUNCTION__<<" :"<<index;
    camera_idx = index - 1;
}


void MainWindow::on_pushButton_start_toggled(bool checked)
{
    qDebug()<<__FUNCTION__<<" checked:"<<checked;
    camview* pp = camview::GetInstance(this);
    if(checked)
    {
        if(camera_idx < 0 || camera_idx > QCameraInfo::availableCameras().count())
        {
            QMessageBox alert(this);
            alert.setText(QString::fromLocal8Bit("请选择有效摄像头！"));
            alert.exec();
            ui->pushButton_start->setChecked(false);
            return;
        }
        camera = new QCamera(QCameraInfo::availableCameras().at(camera_idx),this);
        pp->setupviewfinder(camera);
        camera->start();
    }else{
        if(camera)
        {
            camera->stop();
            delete camera;
            camera = nullptr;
        }
    }
}

void MainWindow::on_camview_closed()
{
    ui->pushButton_preview->setChecked(false);
}
